<template>
  <div style="padding:30px;">
    <el-alert :closable="false" title="商品管理">
      <div class="app-container">
        <el-button @click="addGoodsDialogVisible = true">添加商品</el-button>

        <el-input @change="clearSearch" style="width: 200px;margin-left: 20px" placeholder="请输入关键词" v-model="searchKey"
                  clearable
        />
        <el-button style="margin-left: 20px" @click="searchGoodsByKey">搜索</el-button>

        <br/><br/><br/>
        <el-select @change="setSC" v-model="selectedFir" placeholder="请选择一级分类">
          <el-option
            v-for="(item,index) in firCla"
            :key="item.id"
            :label="item.name"
            :value="index"
          />
        </el-select>
        <el-select @change="setType" v-model="type" placeholder="请选择二级分类" style="margin-left: 20px">
          <el-option
            v-for="item in secCla"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button @click="clearSelect" style="margin-left: 20px;">清除选择</el-button>

        <el-table v-loading="loading" :data="goods" stripe style="width: 100%; margin-top: 30px;">
          <el-table-column prop="id" label="#" width="50"/>
          <el-table-column prop="name" label="名称" width="130"/>
          <el-table-column prop="introduce" label="简介" width="300"/>
          <el-table-column prop="source" label="来源地" width="100"/>
          <el-table-column label="分类" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.firCla }}.</span>
              <span>{{ scope.row.secCla.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="collect" label="收藏人数" width="80"/>
          <el-table-column prop="payments" label="购买次数" width="80"/>
          <el-table-column label="规格" width="100">
            <template slot-scope="scope">
              <el-button type="primary" @click="handleSpu(scope)">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column label="图片" width="100">
            <template slot-scope="scope">
              <el-button type="primary" @click="handlePic(scope)">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button type="primary" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" @click="doDelGoods(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog title="添加商品" :visible.sync="addGoodsDialogVisible">
          <el-form ref="addGoodsForm" :model="addGoodsForm" label-width="120px">
            <el-form-item label="输入商品名">
              <el-input v-model="addGoodsForm.name"/>
            </el-form-item>
            <el-form-item label="输入商品简介">
              <el-input v-model="addGoodsForm.introduce"/>
            </el-form-item>
            <el-form-item label="输入商品货源">
              <el-input v-model="addGoodsForm.source"/>
            </el-form-item>
            <div style="width: 100%; display: flex; justify-content: center;">
              <el-select @change="setSC" v-model="selectedFir" placeholder="请选择一级分类">
                <el-option
                  v-for="(item,index) in firCla"
                  :key="item.id"
                  :label="item.name"
                  :value="index"
                />
              </el-select>
              <el-select v-model="addGoodsForm.classification_id" placeholder="请选择二级分类" style="margin-left: 20px">
                <el-option
                  v-for="item in secCla"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </div>
            <div style="margin-top: 10px; width: 100%; display: flex; flex-direction: column; align-items: center;">
              <p>预览图：</p>
              <el-upload
                :class="{hide:doHideAddPic}"
                :limit=1
                action="none"
                :auto-upload="false"
                list-type="picture-card"
                :on-change="setAddGoodsPicture"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
            <div style="margin-top: 10px; width: 100%; display: flex; flex-direction: column; align-items: center;">
              <p>详情图：</p>
              <el-upload
                :multiple="true"
                action="none"
                :auto-upload="false"
                list-type="picture-card"
                :on-change="setAddGoodsIntroducePicture"
                ref="addDetailUpload"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addGoodsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="doAddGoods">确 定</el-button>
          </div>
        </el-dialog>

        <el-dialog title="修改商品" :visible.sync="updGoodsDialogVisible">
          <el-form ref="updGoodsForm" :model="updGoodsForm" label-width="120px">
            <el-form-item label="输入商品名">
              <el-input v-model="updGoodsForm.name"/>
            </el-form-item>
            <el-form-item label="输入商品简介">
              <el-input v-model="updGoodsForm.introduce"/>
            </el-form-item>
            <el-form-item label="输入商品货源">
              <el-input v-model="updGoodsForm.source"/>
            </el-form-item>
            <el-form-item label="选择所属分类">
              <el-select v-model="updGoodsForm.classificationId" placeholder="请选择分类">
                <el-option-group
                  v-for="fc in firCla"
                  :key="fc.id"
                  :label="fc.name"
                >
                  <el-option
                    v-for="sc in fc.sec"
                    :key="sc.id"
                    :label="sc.name"
                    :value="sc.id"
                  >
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="updGoodsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="doUpdGoods">确 定</el-button>
          </div>
        </el-dialog>

        <el-dialog title="规格管理" :visible.sync="spuDialogVisible">
          <el-table :data="spuData" style="width: 100%">
            <el-table-column label="#" type="index" width="60"/>
            <el-table-column label="规格" width="200">
              <template slot-scope="scope">
                <ul style="margin-left: -20px">
                  <li v-for="(value,key) in scope.row.sku">{{ key }} : {{ value }}</li>
                </ul>
              </template>
            </el-table-column>
            <el-table-column prop="price" width="100" label="单价"/>
            <el-table-column prop="postage" width="100" label="邮费"/>
            <el-table-column prop="stock" width="100" label="库存"/>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="primary" @click="updSpu(scope.row)">修改</el-button>
                <el-button type="danger" @click="delSpu(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="spuAddDialogVisible = true">添加</el-button>
            <el-button @click="spuDialogVisible = false">关闭</el-button>
          </div>
        </el-dialog>

        <el-dialog title="添加" :visible.sync="spuAddDialogVisible">
          <el-form ref="addSpuForm" :model="addSpuForm" label-width="120px">
            <div style="width: 100%; display: flex; justify-content: center;">
              <el-select @change="setSkuVal" v-model="selectedSkuKey" placeholder="选择商品属性">
                <el-option v-for="(sKey,index) in skuKey" :key="sKey.id" :label="sKey.name" :value="index"/>
              </el-select>
              <el-select v-model="selectedSkuVal" placeholder="选择属性值" style="margin-left: 15px">
                <el-option v-for="(v,index) in skuVal" :key="v.id" :label="v.value" :value="index"/>
              </el-select>
              <el-button @click="selectSku" style="margin-left: 15px;">选择</el-button>
            </div>
            <p style="text-align: center;margin: 20px 0;">已选择：{{ selectedSkuWord }}</p>
            <el-form-item label="单价">
              <el-input v-model="addSpuForm.price"/>
            </el-form-item>
            <el-form-item label="库存">
              <el-input v-model="addSpuForm.stock"/>
            </el-form-item>
            <el-form-item label="邮费">
              <el-input v-model="addSpuForm.postage"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addSpu">添加</el-button>
            <el-button @click="spuAddDialogVisible = false">关闭</el-button>
          </div>
        </el-dialog>

        <el-dialog title="修改" :visible.sync="spuUpdDialogVisible">
          <el-form ref="updateSpuForm" :model="updateSpuForm" label-width="120px">
            <el-form-item label="修改单价">
              <el-input v-model="updateSpuForm.price"/>
            </el-form-item>
            <el-form-item label="修改库存">
              <el-input v-model="updateSpuForm.stock"/>
            </el-form-item>
            <el-form-item label="修改邮费">
              <el-input v-model="updateSpuForm.postage"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="spuUpdDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="doUpdSpu">确 定</el-button>
          </div>
        </el-dialog>

        <el-dialog title="图片管理" :visible.sync="picDialogVisible" @close="doHideAddPic = false">
          <p style="margin-top: -20px;">预览图：</p>
          <template>
            <div v-if="pictures!=null" style="height:150px;">
              <el-image style="float: left; width: 150px; height: 150px; margin-left: 20px" :src="pictures.url"
                        :preview-src-list="[pictures.url]"
              />
              <el-button @click="delGoodsPic(pictures.id)" style="float: left; margin-top: 53px; margin-left: 20px"
                         type="danger" icon="el-icon-delete"
                         circle
              />
            </div>
          </template>
          <template>
            <div v-if="pictures==null" style="margin-left: 20px">
              <el-upload
                :limit=1
                :class="{hide:doHideAddPic}"
                action="none"
                :auto-upload="false"
                list-type="picture-card"
                :on-change="setUploadPicture"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
          </template>
          <p>详情图：</p>
          <div style="display: flex; flex-wrap: wrap; ">
            <div v-for="item in introducePic" style="width: 250px; height: 200px;">
              <el-image style=" width: 150px; height: 150px; margin-top: 10px; margin-left: 20px" :src="item.url"
                        :preview-src-list="[item.url]"
              />
              <el-button @click="delGoodsPic(item.id)" style="margin-left: 20px" type="danger" icon="el-icon-delete"
                         circle
              />
            </div>
          </div>
          <el-upload
            style="margin-left: 20px"
            action="none"
            :auto-upload="false"
            list-type="picture-card"
            :on-change="setUploadDetailPicture"
            :multiple="true"
            ref="detailUpload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-button style="margin-left: 20px;margin-top: 20px" @click="doUploadDetailPicture">确认添加</el-button>
        </el-dialog>

        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="page"
          :page-count="totalPage"
          @current-change="handleCurrentChange"
          style="margin-top: 20px"
        />
      </div>
    </el-alert>
  </div>
</template>

<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>

<script>
import {
  getGoods,
  updSpu,
  delSpu,
  getSku,
  addGoodsSpu,
  addGoodsPic,
  delGoodsPic,
  addGoods,
  updGoods,
  delGoods,
  searchGoods
} from '@/api/goods'
import { getFirCla } from '@/api/classification'

export default {
  data() {
    return {
      loading: false,
      page: 1,
      pageSize: 10,
      totalPage: 1,
      type: '',    // 商品分类
      goods: [],
      firCla: [],
      secCla: [],
      selectedFir: '',    // 选中的一级分类数组下标
      addGoodsDialogVisible: false,    // 新增商品对话框
      updGoodsDialogVisible: false,    // 修改商品对话框
      spuDialogVisible: false,    // 商品规格属性管理对话框
      spuUpdDialogVisible: false,    // 商品规格属性修改对话框
      spuAddDialogVisible: false,    // 商品规格属性新增对话框
      picDialogVisible: false,    // 商品图片管理对话框
      spuData: '',    // 记录某商品现有规格属性
      addGoodsForm: {
        name: '',
        introduce: '',
        source: '',
        classification_id: '',
        pictures: ''
      },
      introducePicForAddGoods: '',
      updGoodsForm: {
        id: '',
        name: '',
        introduce: '',
        source: '',
        classificationId: ''
      },
      addSpuForm: {
        gid: '',
        price: '',
        postage: '',
        stock: '',
        sku: []
      },
      updateSpuForm: {
        id: '',
        price: '',
        postage: '',
        stock: ''
      },
      // 添加某商品的规格
      skuKey: [],
      skuVal: [],
      selectedSkuKey: '',
      selectedSkuVal: '',
      selectedSkuWord: [],
      // 图片管理
      pictures: '',
      introducePic: [],
      selectedGid: '',
      doHideAddPic: false,
      searchKey: '',

      selectedGoodsIndex: ''    // 管理时选中的商品
    }
  },
  mounted() {
    this.getSku()
    this.getFC()
    this.getGoods()
  },
  methods: {
    getSku() {
      getSku().then(res => {
        this.skuKey = res.data
      })
    },

    getFC() {
      getFirCla().then(res => {
        this.firCla = res.data
      })
    },

    setSC() {
      this.secCla = this.firCla[this.selectedFir].sec
    },

    setType() {
      this.page = 1
      this.getGoods()
    },

    clearSelect() {
      this.selectedFir = ''
      this.secCla = []
      this.type = ''
      this.getGoods()
    },

    getGoods($op) {
      this.loading = true
      getGoods(this.page, this.pageSize, this.type).then(res => {
        this.totalPage = res.totalPage
        this.goods = res.data
        this.loading = false
        if ($op === 1) {
          this.renewSelectedGoods(this.goods[this.selectedGoodsIndex])
        }
      })
    },

    setAddGoodsPicture(file, fileList) {
      this.addGoodsForm.pictures = file.raw
      if (fileList.length === 1) {
        this.doHideAddPic = true
      }
    },

    setAddGoodsIntroducePicture(file, fileList) {
      this.introducePicForAddGoods = fileList.map((item) => {
        return item.raw
      })
    },

    doAddGoods() {
      addGoods(this.addGoodsForm, this.introducePicForAddGoods).then(res => {
        this.getGoods()
        this.$message('添加成功!')
        this.addGoodsDialogVisible = false
        this.selectedFir = ''
        this.$refs.addDetailUpload.clearFiles()
      })
    },

    handleUpdate($data) {
      this.updGoodsDialogVisible = true
      this.updGoodsForm.id = $data.id
      this.updGoodsForm.name = $data.name
      this.updGoodsForm.introduce = $data.introduce
      this.updGoodsForm.source = $data.source
      this.updGoodsForm.classificationId = $data.classification_id
    },

    doUpdGoods() {
      updGoods(this.updGoodsForm).then(res => {
        this.getGoods()
        this.$message('修改成功')
        this.updGoodsDialogVisible = false
      })
    },

    doDelGoods(gid) {
      delGoods(gid).then(res => {
        this.getGoods()
        this.$message('删除成功')
      })
    },

    handleSpu($data) {
      this.selectedGoodsIndex = $data.$index
      this.spuDialogVisible = true
      this.addSpuForm.gid = $data.row.id
      this.spuData = $data.row.spu
    },

    updSpu($data) {
      this.spuUpdDialogVisible = true
      this.updateSpuForm.id = $data.id
      this.updateSpuForm.postage = $data.postage
      this.updateSpuForm.price = $data.price
      this.updateSpuForm.stock = $data.stock
    },

    doUpdSpu() {
      updSpu(this.updateSpuForm).then(res => {
        this.getGoods()
        this.$message('修改成功!')
        this.spuDialogVisible = false
        this.spuUpdDialogVisible = false
      })
    },

    delSpu(id) {
      delSpu(id).then(res => {
        this.getGoods(1)
        this.$message('删除成功!')
      })
    },

    setSkuVal() {
      this.skuVal = this.skuKey[this.selectedSkuKey].val
    },

    selectSku() {
      let str = this.skuKey[this.selectedSkuKey].id + ',' + this.skuKey[this.selectedSkuKey].val[this.selectedSkuVal].id
      let str2 = this.skuKey[this.selectedSkuKey].name + ' : ' + this.skuKey[this.selectedSkuKey].val[this.selectedSkuVal].value
      this.addSpuForm.sku.push(str)
      this.selectedSkuWord.push(str2)
      this.selectedSkuKey = ''
      this.selectedSkuVal = ''
    },

    addSpu() {
      addGoodsSpu(this.addSpuForm).then(res => {
          this.getGoods(1)
          this.$message('添加成功!')
          this.spuAddDialogVisible = false
          this.addSpuForm.gid = ''
          this.addSpuForm.price = ''
          this.addSpuForm.postage = ''
          this.addSpuForm.stock = ''
          this.addSpuForm.sku = []
          this.selectedSkuWord = []
        }
      )
    },

    handlePic($data) {
      this.selectedGoodsIndex = $data.$index
      this.picDialogVisible = true
      this.pictures = $data.row.picture
      this.introducePic = $data.row.detailPic
      this.selectedGid = $data.row.id
    },

    renewSelectedGoods($data) {
      this.pictures = $data.picture
      this.introducePic = $data.detailPic
      this.selectedGid = $data.id
      this.addSpuForm.gid = $data.id
      this.spuData = $data.spu
    },

    setUploadPicture(file, fileList) {
      addGoodsPic(this.selectedGid, file.raw, '').then(res => {
        this.getGoods(1)
        this.$message('添加成功')
        if (fileList.length === 1) {
          this.doHideAddPic = true
        }
      })
    },

    delGoodsPic(id) {
      delGoodsPic(id).then(res => {
        this.getGoods(1)
        this.doHideAddPic = false
        this.$message('删除成功')
      })
    },

    setUploadDetailPicture(file, fileList) {
      this.detailFileList = fileList.map((item) => {
        return item.raw
      })
    },

    doUploadDetailPicture() {
      addGoodsPic(this.selectedGid, '', this.detailFileList).then(res => {
        this.getGoods(1)
        this.$message('添加成功')
        this.$refs.detailUpload.clearFiles()
      })
    },

    searchGoodsByKey() {
      this.page = 1
      this.doSearch()
    },

    doSearch() {
      this.loading = true
      searchGoods(this.page, this.pageSize, this.searchKey).then(res => {
        this.totalPage = res.totalPage
        this.goods = res.data
        this.loading = false
      })
    },

    clearSearch() {
      if (this.searchKey === '') {
        this.page = 1
        this.getGoods()
      }
    },

    handleCurrentChange(val) {
      this.page = val
      if (this.searchKey !== '') {
        this.doSearch()
      } else {
        this.getGoods()
      }
    }
  }
}
</script>
